<template>
	<view class="self-map-box">
		<view class="map-box">
			<mapView @mapDone="mapDone" ref="mapView" defaultBase="vec"></mapView>
			<view class="map-lefgend-box">
				<view class="map-legend" v-if="legendShow && curType != '3'">
					<template v-if="showLegend == 'danger'">
						<view class="flex-cc" v-for="(item, index) in squareList" :key="index">
							<view class="legend-square" :style="{ background: item.bgColor }"></view>
							<text class="ml10">{{ item.label }}</text>
						</view>
					</template>
					<template v-if="showLegend == 'may'">
						<view class="flex-cc2" v-for="(item, index) in dzAreaTypeList" :key="index">
							<view class="legend-square" :style="{ background: item.bgColor }"></view>
							<text class="ml10">{{ item.label }}</text>
						</view>
					</template>
				</view>
				<view class="map-legend1" v-if="legendShow && curType == '3'">
					<view class="flex-cc1" v-for="(item, index) in dzAreaTypeList" :key="index">
						<view :style="{ background: item.bgColor }" class="legend-square" mode="widthFix" />
						<text class="ml10">{{ item.label }}</text>
					</view>
					<view
						class="flex-cc1"
						v-for="item in dzTypeList"
						:key="item.icon"
						:class="{ noChose: !dzdList_select.includes(item.icon) }"
						@click="clickDzdList(item.icon)"
					>
						<image :src="`/static/image/map/${item.icon}.png`" mode="widthFix" style="width: 30rpx; height: 30rpx" />
						<text class="ml10">{{ item.label }}</text>
					</view>
				</view>
			</view>
			<view class="right-list1" v-if="curType == '2'">
				<view class="icon-type mt20" style="width: 80rpx" @click="fnPreview">
					<i :class="`iconfont icon-fuwenben  fs28`" style="font-size: 34rpx; font-weight: 550"></i>
					<text class="mt7 text nop fs26"> 文本</text>
				</view>
			</view>

			<!-- <view class="right-list">
				<view
					class="icon-type mt20"
					style="width: 80rpx"
					:class="{ 'icon-type-ac': legendShow }"
					@click="legendShow = !legendShow"
				>
					<i :class="`iconfont icon-fenlei  fs28`" style="font-size: 34rpx; font-weight: 550"></i>
					<text class="mt7 text nop fs26"> 图例</text>
				</view>
			</view> -->
		</view>

		<scroll-view scroll-y class="main-box">
			<sh v-if="curType == '2'" @getSh="getShJson" @getLegend="getLegend"></sh>
			<dz v-if="curType == '3'"></dz>
			<hd v-if="curType == '4'" @getHd="getHdJson" @getLegend="getLegend"></hd>
		</scroll-view>
	</view>
</template>

<script>
	import indexApi from '@/api/index.js'
	import warnApi from '@/api/monitor/warn.js'
	import sh from './sh.vue'
	import dz from './dz.vue'
	import hd from './hd.vue'
	export default {
		name: 'cmMap',
		components: { sh, dz, hd },
		props: {
			showType: {
				type: String,
				default: ''
			}
		},
		watch: {
			showType: {
				handler(newVal, oldVal) {
					this.curType = newVal
					if (this.map && this.layerGroups.dzSites) {
						this.layerGroups.dzSites.clearLayers()
					}
					if (this.map && this.layerGroups.river) {
						this.layerGroups.river.clearLayers()
					}
					if (this.map && this.layerGroups.shLayer) {
						this.layerGroups.shLayer.clearLayers()
					}
					if (this.curType == '3') {
						this.initDzData()
					}
				},
				immediate: true
			}
		},
		data() {
			return {
				curType: 1,
				map: null,
				legendShow: true,
				squareList: [
					{
						label: '危险',
						bgColor: '#ff0000'
					},
					{
						label: '警戒',
						bgColor: '#FF9B00'
					},
					{
						label: '警示',
						bgColor: '#FFFF00'
					},
					{
						label: '注意',
						bgColor: '#0000FF'
					}
				],
				dzAreaTypeList: [
					{
						label: '可能性很大',
						bgColor: '#ff0000'
					},
					{
						label: '可能性大',
						bgColor: '#FF9B00'
					},
					{
						label: '可能性较大',
						bgColor: '#FFFF00'
					},
					{
						label: '可能发生',
						bgColor: '#0000FF'
					}
				],
				dzTypeList: [
					{
						label: '崩塌',
						icon: 'dzd-bt',
						field: 'COLLAPSE',
						color: '#9e2bf7'
					},
					{
						label: '地面崩塌',
						icon: 'dzd-dmbt',
						field: 'GROUNDCOLLAPSE',
						color: '#fbbd30'
					},
					{
						label: '泥石流',
						icon: 'dzd-nsl',
						field: 'DEBRISFLOW',
						color: '#0dd48c'
					},
					{
						label: '滑坡',
						icon: 'dzd-hp',
						field: 'LANDSLIDE',
						color: '#3e81ee'
					},
					{
						label: '高陡边坡',
						icon: 'dzd-gdbp',
						field: 'HIGHSTEEPSLOPE',
						color: '#c83d35'
					}
				],

				dzdList_select: ['dzd-bt', 'dzd-dmbt', 'dzd-nsl'],

				markers: null,
				hdJson: [],
				shList: [],
				countyJson: [],
				townJson: [],
				isShRender: null,
				showLegend: 'danger'
			}
		},
		methods: {
			mapDone(map) {
				this.map = map
				// 初始化图层组
				this.mapGroups = L.baseLayerGroup().addTo(map)

				const addLayerEv = (key) => {
					let layer = L.baseLayerGroup()
					layer.key = key
					this.mapGroups.addLayer(layer)
					return layer
				}
				this.layerGroups = {
					river: addLayerEv('river'),
					dzSites: addLayerEv('dzSites'),
					shLayer: addLayerEv('shLayer'),
					countyLayer: addLayerEv('countyLayer')
				}
				this.map.on('zoomend', (e) => {
					let zoom = e.target.getZoom()
					this.getShJsonByzoom(zoom)
				})
				// this.$refs.mapView.getBoundsByCode(350400)
				this.getCountyLayer()
				this.getTownLayer()
			},
			getLegend(idx) {
				let curLegend = idx != 2 ? 'danger' : 'may'
				if (this.showLegend != curLegend) {
					this.showLegend = curLegend
				}
			},
			async getCountyLayer() {
				let resp = await indexApi.getCounty()
				this.countyJson = resp.features
				L.geoJSON(resp, {
					pane: 'tilePane',
					style: function (feature) {
						return { fill: false, fillOpacity: 0, weight: 1, color: '#4c4848' }
					}
				})
					.setStyle({
						className: 'mapLine' // 手势设置
					})
					.addTo(this.layerGroups.countyLayer)
			},
			async getTownLayer() {
				let resp = await indexApi.getTown()
				this.townJson = resp.features
			},
			getShJson(list) {
				this.shList = list
				this.isShRender = null
				if (this.map) {
					let zoom = this.map.getZoom()
					this.getShJsonByzoom(zoom)
				}
			},
			async getShJsonByzoom(zoom) {
				if (this.shList.length == 0 || this.curType != '2') {
					return
				}
				if (zoom < 9) {
					if (this.isShRender == 'county') {
						return
					}
					// 乡镇
					if (this.countyJson.length == 0) {
						await this.getCountyLayer()
					}
					this.layerGroups.shLayer.clearLayers()
					let record = []
					this.shList.forEach((item) => {
						item.ContryList.forEach((cItem) => {
							let recordFObj = record.find((fItem) => fItem == cItem.Addvcd)
							// 判断是否已经上色，按数据顺序红色优先级最高
							if (!recordFObj) {
								let fObj = this.countyJson.find((fItem) => fItem.properties.code == cItem.Addvcd)
								if (fObj) {
									let color = this.squareList[item.Level - 1].bgColor
									L.geoJSON(fObj, {
										pane: 'tilePane',
										style: function (feature) {
											return { fill: true, fillOpacity: 0.6, weight: 1, color: '#000', fillColor: color }
										}
									})
										.setStyle({
											className: 'mapLine' // 手势设置
										})
										.addTo(this.layerGroups.shLayer)
									record.push(cItem.Addvcd)
								}
							}
						})
					})
					this.isShRender = 'county'
				} else {
					if (this.isShRender == 'town') {
						return
					}
					// 县
					if (this.townJson.length == 0) {
						await this.getTownLayer()
					}
					this.layerGroups.shLayer.clearLayers()
					let record = []
					this.shList.forEach((item) => {
						item.ContryList.forEach((cItem) => {
							cItem.TwonList.forEach((tItem) => {
								let recordFObj = record.find((fItem) => fItem == tItem.TwonAddvcd)
								// 判断是否已经上色，按数据顺序红色优先级最高
								if (!recordFObj) {
									let fObj = this.townJson.find((fItem) => fItem.properties.code == tItem.TwonAddvcd)
									if (fObj) {
										let color = this.squareList[item.Level - 1].bgColor
										L.geoJSON(fObj, {
											pane: 'tilePane',
											style: function (feature) {
												return { fill: true, fillOpacity: 0.6, weight: 1, color: '#000', fillColor: color }
											}
										})
											.setStyle({
												className: 'mapLine' // 手势设置
											})
											.addTo(this.layerGroups.shLayer)
										record.push(tItem.TwonAddvcd)
									}
								}
							})
						})
					})
					this.isShRender = 'town'
				}
			},
			async getHdJson(list) {
				if (this.hdJson.length == 0) {
					// let res = await warnApi.getHdJson()
					// this.hdJson = res.features
					let resp = await indexApi.getTown()
					this.townJson = resp.features
					console.info(`this.townJson:`, this.townJson)
				}
				if (this.map) {
					this.layerGroups.river.clearLayers()
				}
				console.info(`list:`, list)
				console.info(`this.hdJson:`, this.hdJson)
				list.forEach((item) => {
					console.info(`item:`, item)
					let color = this.squareList[item.Level - 1].bgColor
					item.ContryList.forEach((countyItem) => {
						countyItem.TwonList.forEach((townItem) => {
							// let obj = this.hdJson.find((fItem) => fItem.properties.BWSCD == townItem.TwonAddvcd)
							let obj = this.townJson.find((fItem) => fItem.properties.code == townItem.TwonAddvcd)
							if (obj) {
								L.geoJSON(obj, {
									pane: 'tilePane',
									style: function (feature) {
										return { fill: true, fillOpacity: 0.51, weight: 5, color: color }
									}
								}).addTo(this.layerGroups.river)
							}
						})
					})
				})
				this.$hideLoading()
			},
			async fnPreview() {
				let obj = {
					title: '山洪灾害文本',
					type: 'sh'
				}
				uni.navigateTo({ url: `/pages-subPackages/monitor/shPdf?title=${obj.title}&type=${obj.type}` })
			},

			clickDzdList(value) {
				let index = this.dzdList_select.findIndex((el) => el == value)
				if (index > -1) {
					this.dzdList_select.splice(index, 1)
				} else {
					this.dzdList_select.push(value)
				}
				this.$nextTick(() => {
					this.initDzData()
				})
			},
			async initDzData() {
				// if (this.markers) {
				// 	this.layerGroups.dzSites.addLayer(this.markers)
				// 	return
				// }
				let params = {
					service: 'WFS',
					request: 'GetFeature',
					version: '1.0.0',
					outputFormat: 'application/json',
					maxFeatures: '10000',
					typeName: 'sanming:地质灾害点',
					filter: `<Filter xmlns="http://www.opengis.net/ogc" xmlns:gml="http://www.opengis.net/gml"><And> <PropertyIsLike wildCard="*" singleChar="#" escapeChar="!">
                      <PropertyName>disasterTy</PropertyName>
                      <Literal>*COLLAPSE*</Literal>
                  </PropertyIsLike></And></Filter>`
				}
				let res = []
				if (!this.DzSite) {
					this.DzSite = await warnApi.getDzSite(params)
					res = this.DzSite
				} else {
					res = this.DzSite
				}
				this.layerGroups.dzSites.clearLayers()
				var markers = L.markerClusterGroup().addTo(this.layerGroups.dzSites)
				res.features.forEach((item) => {
					let obj = this.dzTypeList.find((fItem) => fItem.field == item.properties.disasterTy)
					if (obj) {
						let icon = obj.icon
						if (!this.dzdList_select.includes(icon)) {
							return
						}
						let tip = `
						<div>
										<div style="display:flex;align-items:center;margin-bottom:5px">
											<img src="/static/image/map/${icon}.png" style='position:relative;bottom:2px;width:18px;margin-right:5px' alt="" srcset=""/>
											<div style="font-size:16px">地灾隐患点</div>
										</div>
										<div style="margin-bottom: 5px">类型：${obj.label}</div>
										<div style="margin-bottom: 5px">位置：${item.properties.geograPosi}</div>
										<div style="margin-bottom: 5px">名称：${item.properties.disasterNa}</div>
										</div>
						`
						markers.addLayer(
							L.marker([item.properties.latitude, item.properties.longitude], {
								icon: L.divIcon({
									className: 'map-town-legend-style',
									iconSize: [25, 25],
									html: `<img src="/static/image/map/${icon}.png" style='width:25px' alt="" srcset=""/>`
								})
							}).bindPopup(tip)
						)
					}
				})
				// this.markers = markers
			}
		},
		mounted() {}
	}
</script>
<style lang="less" scoped>
	.self-map-box {
		width: 100%;
		height: 100%;
		overflow: hidden;
		.map-box {
			width: 100%;
			height: 800rpx;
			position: relative;

			.map-lefgend-box {
				position: absolute;
				width: 100%;
				z-index: 999;
				bottom: 40rpx;
			}
			.map-legend-cm {
				margin: 0 auto;
				background: #fff;
				display: flex;
				align-items: center;
				border-radius: 12rpx;
				box-shadow: 0px 4rpx 30rpx rgba(0, 0, 0, 0.28);
				.ml10 {
					font-size: 24rpx;
				}
				.flex-cc1 {
					display: flex;
					align-items: center;
					width: 33%;
					margin-bottom: 20rpx;
				}
				.flex-cc {
					margin: 0rpx 12rpx 0rpx 12rpx;
				}
				.flex-cc2 {
					display: flex;
					align-items: center;
					justify-content: center;
					margin-right: 12rpx;
				}

				.legend-square {
					width: 30rpx;
					height: 30rpx;
					border-radius: 8rpx;
					margin-right: 5rpx;
				}
			}
			.map-legend {
				width: 90%;
				height: 70rpx;
				justify-content: center;
				.map-legend-cm;
			}
			.map-legend1 {
				width: 90%;
				flex-wrap: wrap;
				justify-content: flex-start;
				padding: 20rpx 0 0 5%;
				.map-legend-cm;
			}

			.right-list {
				position: absolute;
				right: 20rpx;
				bottom: 180rpx;
				z-index: 999;
			}

			.right-list1 {
				position: absolute;
				right: 10rpx;
				top: 20rpx;
				z-index: 999;
			}
		}

		.main-box {
			height: calc(100% - 780rpx);
			position: relative;
			bottom: 20rpx;
			z-index: 999;
			border-top-left-radius: 20rpx;
			border-top-right-radius: 20rpx;
			padding: 20rpx 20rpx 0 20rpx;
			background: #fff;
		}
	}
	.noChose {
		filter: gray;
		filter: grayscale(100%);
		-webkit-filter: grayscale(100%);
		-moz-filter: grayscale(100%);
		-ms-filter: grayscale(100%);
		-o-filter: grayscale(100%);
	}
</style>
